package com.dubbo.sbdprovider.jdbcutil;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * @author sola
 */
public class JdbcUtil {

    public static Connection getConnection() throws SQLException, ClassNotFoundException {
        final String url="jdbc:mysql://127.0.0.1:3307/stat?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8";
        final String user="root";
        final String password="root";
         Class.forName("com.mysql.cj.jdbc.Driver");
        return DriverManager.getConnection(url,user,password);
    }

    @SuppressWarnings("unchecked")
    public static List<HashMap> queryList(String sql) throws SQLException, ClassNotFoundException {
        Connection connection = getConnection();
        final Statement statement = connection.createStatement();
        final ResultSet resultSet = statement.executeQuery(sql);
        final ResultSetMetaData metaData = resultSet.getMetaData();
        HashMap<String,Object> map = new HashMap(64);
        ArrayList<HashMap> arrayList = new ArrayList();
        while(resultSet.next()){
            map.clear();
            for(int i=0;i<metaData.getColumnCount();i++) {
                final String columnLabel = metaData.getColumnLabel(i+1);
                final Object object = resultSet.getObject(columnLabel);
                map.put(columnLabel.replaceAll("_","").toLowerCase(),object);
            }
/*            final Class aClass = entity.getClass();

            final T o = (T) entity.getClass().newInstance();
            final Field[] fields = aClass.getDeclaredFields();
            for(Field field:fields){
                field.setAccessible(Boolean.TRUE);
                field.set(o,map.get(field.getName().toLowerCase()));
            }*/

            arrayList.add(map);
        }
        return arrayList;
    }

}
